package cn.boysoft.core.server.netty.codec;

import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH;
import static org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static org.jboss.netty.handler.codec.http.HttpResponseStatus.OK;
import static org.jboss.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.http.DefaultHttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import org.jboss.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import cn.boysoft.core.model.message.json.JSONResponse;
/**
 * @author 付厚俊
 * CreateTime 2013-4-4 下午5:09:32
 */
@Service(value="jsonResponseEncoder")
@Scope(value="prototype")
public class JsonResponseEncoder extends OneToOneEncoder{
	private final static Logger LOGGER = LoggerFactory.getLogger(JsonResponseEncoder.class);
	@Override
	protected Object encode(ChannelHandlerContext context, Channel channel,
			Object object) throws Exception {
		
		if (object instanceof JSONResponse) {
			JSONResponse JsonResponse = (JSONResponse)object;
			String content = JsonResponse.toJson();
			LOGGER.debug("JsonResponse :"+content);
			HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
			response.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");
			response.setContent(ChannelBuffers.copiedBuffer(content, CharsetUtil.UTF_8));
			response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());
			LOGGER.debug("HttpResponse :"+response.toString());
            return response;
        }
		return object;
	}

}
